package com.mh.study.streams;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author meng.han
 * @since 2022-01-17
 */
public class LazyInvocation {

    private long counter;

    private void wasCalled() {
        counter++;
    }

    /**
     * 中间操作是惰性的，终端操作时才会执行中间操作
     */
    public long lazy() {
        List<String> list = Arrays.asList("abc1", "abc2", "abc3");
        counter = 0;
        Stream<String> stream = list.stream().filter(element -> {
            wasCalled();
            return element.contains("2");
        });
        if (counter != 0) {
            throw new IllegalStateException();
        }
        stream.count();
        return counter;
    }

}
